package vip.xiaonuo.modular.callback;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.base.Joiner;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.Reactor;
import reactor.event.Event;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.memberuser.service.MemberUserService;
import vip.xiaonuo.facedoor.modular.topic.EventTopic;
import vip.xiaonuo.facedoor.modular.visitor.entity.Visitor;
import vip.xiaonuo.facedoor.modular.visitor.service.VisitorService;
import vip.xiaonuo.modular.remoteapi.card.RemoteCardConstant;
import vip.xiaonuo.modular.remoteapi.card.RemoteCardConstant.CardStatus;
import vip.xiaonuo.modular.remoteapi.stairs.RemoteStairsConstant;
import vip.xiaonuo.modular.remoteapi.stairs.RemoteStairsConstant.DeviceSyncStatus;
import vip.xiaonuo.modular.remoteapi.stairs.RemoteStairsConstant.ElevatorFiledStatus;
import vip.xiaonuo.modular.remoteapi.stairs.RemoteStairsConstant.MemberSyncStatus;
import vip.xiaonuo.modular.remoteapi.stairs.RemoteStairsConstant.RequestCmd;
import vip.xiaonuo.modular.remoteapi.stairs.response.DeviceDTO;
import vip.xiaonuo.modular.remoteapi.stairs.response.PersonsDTO;
import vip.xiaonuo.modular.sync.DeviceEvent;
import vip.xiaonuo.modular.util.CardConverseUtil;
import vip.xiaonuo.modular.ybuildingmemberrl.entity.YBuildingMemberRl;
import vip.xiaonuo.modular.ybuildingmemberrl.mapper.YBuildingMemberRlMapper;
import vip.xiaonuo.modular.ybuildingmemberrl.param.YBuildingMemberRlParam;
import vip.xiaonuo.modular.ybuildingmemberrl.service.YBuildingMemberRlService;
import vip.xiaonuo.modular.ybuildingvisitorrl.entity.YBuildingVisitorRl;
import vip.xiaonuo.modular.ybuildingvisitorrl.mapper.YBuildingVisitorRlMapper;
import vip.xiaonuo.modular.ybuliding.entity.YBuliding;
import vip.xiaonuo.modular.ybuliding.mapper.YBulidingMapper;
import vip.xiaonuo.modular.ycarddevice.entity.YCardDevice;
import vip.xiaonuo.modular.ycarddevice.param.YCardDeviceParam;
import vip.xiaonuo.modular.ycarddevice.service.YCardDeviceService;
import vip.xiaonuo.modular.ydeviceevent.entity.YDeviceEvent;
import vip.xiaonuo.modular.ydeviceevent.mapper.YDeviceEventMapper;
import vip.xiaonuo.modular.yelevatordevice.entity.YElevatorDevice;
import vip.xiaonuo.modular.yelevatordevice.service.YElevatorDeviceService;
import vip.xiaonuo.modular.yelevatormemberrecord.entity.YElevatorMemberRecord;
import vip.xiaonuo.modular.yelevatormemberrecord.service.YElevatorMemberRecordService;
import vip.xiaonuo.modular.yelevatorvisitormemberrecord.entity.YElevatorVisitorMemberRecord;
import vip.xiaonuo.modular.yelevatorvisitormemberrecord.service.YElevatorVisitorMemberRecordService;
import vip.xiaonuo.modular.ymemberrecord.entity.YMemberRecord;
import vip.xiaonuo.modular.ymemberrecord.mapper.YMemberRecordMapper;
import vip.xiaonuo.modular.ymemberrecord.service.YMemberRecordService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/a/v1.0/callback/stairs")
@Slf4j
public class CallBackController {

  @Autowired
  private YCardDeviceService cardDeviceService;

  @Autowired
  private YElevatorDeviceService elevatorDeviceService;

  @Autowired
  private MemberUserService memberService;

  @Autowired
  private YBuildingMemberRlService buildingMemberService;

    @Resource
    private YBuildingVisitorRlMapper buildingVisitorRlMapper;

    @Resource
    private YBuildingMemberRlMapper buildingMemberRlMapper;

  @Autowired
  private VisitorService visitorService;

  @Autowired
  private YElevatorVisitorMemberRecordService visitorMemberRecordService;

  @Autowired
  private YElevatorMemberRecordService memberRecordService;

  @Resource
  private YBulidingMapper bulidingMapper;


  @Resource
  private YDeviceEventMapper eventEntityMapper;

  @Resource
  private YMemberRecordMapper memberRecordMapper;
  @Resource
  private YMemberRecordService yMemberRecordService;

  @Resource
  private Reactor reactor;

  public static final String VERSION = "version";
  public static final String CMD = "cmd";
  public static final String CMD_NUMBER = "cmd_number";
  public static final String DATE_TIME = "date_time";
  public static final Integer MEMBER=1;
  public static final Integer VISITOR=2;

  @RequestMapping(method = RequestMethod.POST, value = "callback")
  public void callback(@RequestBody CallBackDto callBackDto, HttpServletResponse response) {
    try {
      log.info("收到铁虎设备回调记录【{}】", callBackDto);
      Map<String, Object> returnMap = new HashMap<>(16);
      YCardDevice cardDevice = cardDeviceService.getByParam(new YCardDeviceParam().setDeviceNo(callBackDto.getDevice_no()));
      YElevatorDevice elevatorDevice = elevatorDeviceService.getByParam(new YElevatorDevice().setDeviceNo(callBackDto.getDevice_no()));

      // 发卡器
      if (cardDevice != null) {
        card(callBackDto, returnMap, cardDevice);
        // 电梯
      } else if (elevatorDevice != null) {
          // 处理异常事件
          if (Objects.nonNull(callBackDto.getCmd_number())) {
              eventEntityMapper.updateRequestAndResponse(callBackDto.getCmd_number(), null, JSON.toJSONString(callBackDto));
              if ((callBackDto.getCode() != null && callBackDto.getCode() != 0) || StringUtils.isNotBlank(callBackDto.getErr_desc())) {
                dealErrorEvent(callBackDto, elevatorDevice);
                return;
              }
          }

        // 处理返回事件
        dealEvent(callBackDto, returnMap, elevatorDevice);

        // 获取下一个事件
        responseEvent(callBackDto, returnMap, elevatorDevice);
      } else {
        log.error("无效的设备【{}】！", callBackDto.getDevice_no());
      }

      // 响应数据
      returnResponseToDevice(response, returnMap);
    } catch (Exception e) {
        e.printStackTrace();
      log.info("铁虎回调失败【{}】", ExceptionUtils.getMessage(e));
    }
  }

  private void dealErrorEvent(CallBackDto callBackDto, YElevatorDevice elevatorDevice) {
    YDeviceEvent event = eventEntityMapper.selectById(callBackDto.getCmd_number());
    eventEntityMapper.updateError(callBackDto.getCmd_number());
    if (StringUtils.isNotBlank(callBackDto.getCmd())) {
      switch (event.getType()) {
        case RequestCmd.UPDATE_PERSON:
            // 区分人员还是访客
            if (Objects.equals(event.getSysType(),MEMBER)){
                updatePersonError(elevatorDevice, event);
                // 区分人员还是访客
            }else if (Objects.equals(event.getSysType(),VISITOR)){
                updateVisitorError(elevatorDevice, event);
            }
          break;
        case RequestCmd.ADD_PERSON:
            // 区分人员还是访客
            if (Objects.equals(event.getSysType(),MEMBER)){
                addPersonError(elevatorDevice, event);
                // 区分人员还是访客
            }else if (Objects.equals(event.getSysType(),VISITOR)){
                addVisitorError(elevatorDevice, event);
            }
          break;
        case RequestCmd.BATCH_ADD_PERSON:
            // 区分人员还是访客
            if (Objects.equals(event.getSysType(),MEMBER)){
                batchAddPersonError(elevatorDevice, event);
                // 区分人员还是访客
            }else if (Objects.equals(event.getSysType(),VISITOR)){
                batchAddVisitorError(elevatorDevice, event);
            }
          break;
      }
    }
  }

  private void batchAddPersonError(YElevatorDevice elevatorDevice, YDeviceEvent event) {
    for (String memberRlId : event.getBody().split(",")) {
      YBuildingMemberRl yBuildingMemberRl = buildingMemberService.getById(memberRlId);
      yBuildingMemberRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_ERROR);
      buildingMemberRlMapper.updateById(yBuildingMemberRl);
    }
    elevatorDevice.setMemberSyncStatus(MemberSyncStatus.SYNC_ERROR);
    elevatorDeviceService.updateById(elevatorDevice);
  }

    private void batchAddVisitorError(YElevatorDevice elevatorDevice, YDeviceEvent event) {
        for (String visitorRl : event.getBody().split(",")) {
            YBuildingVisitorRl buildingVisitorRl = buildingVisitorRlMapper.selectById(visitorRl);
            buildingVisitorRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_ERROR);
            buildingVisitorRlMapper.updateById(buildingVisitorRl);
        }
        elevatorDevice.setMemberSyncStatus(MemberSyncStatus.SYNC_ERROR);
        elevatorDeviceService.updateById(elevatorDevice);
    }

  private void addPersonError(YElevatorDevice elevatorDevice, YDeviceEvent event) {
    YBuildingMemberRl yBuildingMemberRl = buildingMemberService.getById(event.getBody());
    yBuildingMemberRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_ERROR);
    buildingMemberService.updateById(yBuildingMemberRl);
    elevatorDevice.setMemberSyncStatus(MemberSyncStatus.SYNC_ERROR);
    elevatorDeviceService.updateById(elevatorDevice);
  }

    private void addVisitorError(YElevatorDevice elevatorDevice, YDeviceEvent event) {
        String memberRl = event.getBody();
        YBuildingVisitorRl yBuildingVisitorRl = buildingVisitorRlMapper.selectById(memberRl);
        yBuildingVisitorRl.setDeviceSyncStatus(RemoteStairsConstant.DeviceSyncStatus.SYNC_ERROR);
        buildingVisitorRlMapper.updateById(yBuildingVisitorRl);
        elevatorDevice.setMemberSyncStatus(MemberSyncStatus.SYNC_ERROR);
        elevatorDeviceService.updateById(elevatorDevice);
    }

  private void updatePersonError(YElevatorDevice elevatorDevice, YDeviceEvent event) {
    String memberRl = event.getBody();
    YBuildingMemberRl yBuildingMemberRl = buildingMemberRlMapper.selectById(memberRl);
    yBuildingMemberRl.setDeviceSyncStatus(RemoteStairsConstant.DeviceSyncStatus.SYNC_ERROR);
    buildingMemberRlMapper.updateById(yBuildingMemberRl);
    elevatorDevice.setMemberSyncStatus(MemberSyncStatus.SYNC_ERROR);
    elevatorDeviceService.updateById(elevatorDevice);
  }

    private void updateVisitorError(YElevatorDevice elevatorDevice, YDeviceEvent event) {
        String memberRl = event.getBody();
        YBuildingVisitorRl yBuildingVisitorRl = buildingVisitorRlMapper.selectById(memberRl);
        yBuildingVisitorRl.setDeviceSyncStatus(RemoteStairsConstant.DeviceSyncStatus.SYNC_ERROR);
        buildingVisitorRlMapper.updateById(yBuildingVisitorRl);
        elevatorDevice.setMemberSyncStatus(MemberSyncStatus.SYNC_ERROR);
        elevatorDeviceService.updateById(elevatorDevice);
    }

  private void returnResponseToDevice(HttpServletResponse response, Map<String, Object> returnMap) throws IOException {

    response.setContentType("application/json;charset=gbk");
    String result = JSON.toJSONString(returnMap);
    if (Objects.nonNull(returnMap.get("cmd_number"))) {
      eventEntityMapper.updateRequestAndResponse((Integer) returnMap.get("cmd_number"), result, null);
    }
    log.info("返回设备参数【{}】", result);
    response.setContentLength(result.length());
    PrintWriter writer = response.getWriter();
    writer.println(result);
    response.flushBuffer();
  }

  private void responseEvent(CallBackDto callBackDto, Map<String, Object> returnMap, YElevatorDevice elevatorDevice) {
    if (Objects.equals(RequestCmd.BROWSE_PERSONS, callBackDto.getCmd())) {
      if (callBackDto.getCount() == 8) {
        returnMap.put(VERSION, callBackDto.getVersion());
        returnMap.put(CMD, RequestCmd.BROWSE_PERSONS);
        returnMap.put(CMD_NUMBER, 1);
        returnMap.put("page_no", callBackDto.getPage_no() + 1);
        returnMap.put("page_size", 8);
        return;
      }
    }
    // 查询事件处理
    YDeviceEvent event = eventEntityMapper.findOne(elevatorDevice.getDeviceNo());
    try {
      if (event != null) {
        switch (event.getType()) {

          // 人员数据浏览
          case RequestCmd.BROWSE_PERSONS:
              browsePersons(callBackDto, returnMap, event);
              break;

          // 同步设备时间
          case RequestCmd.UPDATE_SYSTEM_TIME:
            updateSystemTime(callBackDto, returnMap, event);
            break;

          // 获取设备参数
          case RequestCmd.REQUEST_DEVICE_PARAMS:
            requestDeviceParams(callBackDto, returnMap, event);
            break;

          // 修改设备参数
          case RequestCmd.UPDATE_DEVICE_PARAMS:
            updateDeviceParams(callBackDto, returnMap, event);
            break;

          // 新增人员
          case RequestCmd.ADD_PERSON:
            addPerson(callBackDto, returnMap, event);
            break;

          // 删除人员
          case RequestCmd.DELETE_PERSON:
            deletePerson(callBackDto, returnMap, event);
            break;

            // 当前删除人员
        case RequestCmd.CURRENT_DELETE_PERSON:
            currentDeletePerson(callBackDto, returnMap, event);
            break;

            // 删除全部人员信息
          case RequestCmd.DELETE_ALL_PERSON:
            deleteAllPerson(callBackDto, returnMap, event);
            break;

          // 建筑发生变更 第二步批量增加人员
          case RequestCmd.BATCH_ADD_PERSON:
            batchAddPerson(callBackDto, returnMap, event, elevatorDevice);
            break;

          // 修改人员
          case RequestCmd.UPDATE_PERSON:
            updatePerson(callBackDto, returnMap, event);
            break;

          // 消防通道
          case RequestCmd.SET_FIRE:
              setFire(callBackDto, returnMap, event);
              break;

        }
      }
    } catch (Exception e) {
        e.printStackTrace();
      event.setStatus("LOCAL_ERROR");
      event.setResponse(ExceptionUtils.getMessage(e));
      eventEntityMapper.updateById(event);
      log.error("本地任务发生异常【{}】", ExceptionUtils.getMessage(e));
    }

  }

    private void setFire(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
        returnMap.put(VERSION, callBackDto.getVersion());
        returnMap.put(CMD, RequestCmd.SET_FIRE);
        returnMap.put(CMD_NUMBER, event.getId());
        returnMap.put("enable", Boolean.valueOf(event.getBody()));
    }

    private void browsePersons(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
        returnMap.put(VERSION, callBackDto.getVersion());
        returnMap.put(CMD, RequestCmd.BROWSE_PERSONS);
        returnMap.put(CMD_NUMBER, event.getId());
        if (StringUtils.isNotBlank(event.getBody())) {
          returnMap.put("page_no", Integer.parseInt(event.getBody()));
        } else {
          returnMap.put("page_no", 1);
        }
        returnMap.put("page_size", 8);
    }

    private void updatePerson(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
        // 区分人员还是访客
        if (Objects.equals(event.getSysType(),MEMBER)){
            updateMember(callBackDto, returnMap, event);
            // 区分人员还是访客
        }else if (Objects.equals(event.getSysType(),VISITOR)){
            updateVisitor(callBackDto, returnMap, event);
        }
    }

    private void updateMember(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
        String memberRl = event.getBody();
        YBuildingMemberRl yBuildingMemberRl = buildingMemberRlMapper.selectById(memberRl);
        MemberUser member = memberService.getById(yBuildingMemberRl.getMemberId());
        try {
          returnMap.put(VERSION, callBackDto.getVersion());
          returnMap.put(CMD, RequestCmd.UPDATE_PERSON);
          returnMap.put(CMD_NUMBER, event.getId());
          returnMap.put("id", Long.parseLong("1"+member.getId()));
          returnMap.put("name", " ");
          if (StringUtils.isNotBlank(yBuildingMemberRl.getLiveFloor())) {
            returnMap.put("live_floor", Integer.valueOf(yBuildingMemberRl.getLiveFloor()));
          }
          if (StringUtils.isNotBlank(yBuildingMemberRl.getHandFloor())) {
            List<Integer> collect = Arrays.stream(yBuildingMemberRl.getHandFloor().split(",")).map(Integer::valueOf).collect(Collectors.toList());
            returnMap.put("hand_floor", collect);
            returnMap.put("hand_floor_count", collect.size());
          }
          if (StringUtils.isNotBlank(member.getIcCard())){
              returnMap.put("wg_card_id", CardConverseUtil.converseTo10Card(member.getIcCard()));
          }else {
              returnMap.put("wg_card_id","");
          }
          returnMap.put("term", "forever");
        } catch (Exception e) {
          yBuildingMemberRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_ERROR);
          buildingMemberRlMapper.updateById(yBuildingMemberRl);
          event.setStatus("LOCAL_ERROR");
          event.setResponse(ExceptionUtils.getMessage(e).concat("============".concat(member.getName()).concat("=====").concat(member.getId().toString())));
          eventEntityMapper.updateById(event);
          log.error("本地任务发生异常【{}】", ExceptionUtils.getMessage(e));
        }
    }


    private void updateVisitor(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
        YBuildingVisitorRl yBuildingVisitorRl = buildingVisitorRlMapper.selectById(event.getBody());
        Visitor visitor = visitorService.getById(yBuildingVisitorRl.getVisitorId());
        try {
            returnMap.put(VERSION, callBackDto.getVersion());
            returnMap.put(CMD, RequestCmd.UPDATE_PERSON);
            returnMap.put(CMD_NUMBER, event.getId());
            returnMap.put("id", Long.parseLong("2"+visitor.getId()));
            returnMap.put("name", " ");
            if (StringUtils.isNotBlank(yBuildingVisitorRl.getLiveFloor())) {
                returnMap.put("live_floor", Integer.valueOf(yBuildingVisitorRl.getLiveFloor()));
            }
            if (StringUtils.isNotBlank(yBuildingVisitorRl.getHandFloor())) {
                List<Integer> collect = Arrays.stream(yBuildingVisitorRl.getHandFloor().split(",")).map(Integer::valueOf).collect(Collectors.toList());
                returnMap.put("hand_floor", collect);
                returnMap.put("hand_floor_count", collect.size());
            }
            if (StringUtils.isNotBlank(visitor.getIcCard())){
                returnMap.put("wg_card_id", CardConverseUtil.converseTo10Card(visitor.getIcCard()));
            }else {
                returnMap.put("wg_card_id", "");
            }
            returnMap.put("term", "forever");
        } catch (Exception e) {
            e.printStackTrace();
            yBuildingVisitorRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_ERROR);
            buildingVisitorRlMapper.updateById(yBuildingVisitorRl);
            event.setStatus("LOCAL_ERROR");
            event.setResponse(ExceptionUtils.getMessage(e).concat("============".concat(visitor.getName()).concat("=====").concat(visitor.getId().toString())));
            eventEntityMapper.updateById(event);
            log.error("本地任务发生异常【{}】", ExceptionUtils.getMessage(e));
        }
    }
    private void batchAddPerson(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event, YElevatorDevice elevatorDevice) {
        // 区分人员还是访客
        if (Objects.equals(event.getSysType(),MEMBER)){
            batchAddMember(callBackDto, returnMap, event);
            // 区分人员还是访客
        }else if (Objects.equals(event.getSysType(),VISITOR)){
            batchAddVisitor(callBackDto, returnMap, event);
        }
    }

    private void batchAddMember(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
        String memberIds = event.getBody();
        List<PersonsDTO> persons = new ArrayList<>();
        try {
          for (String memberRlId : memberIds.split(",")) {
            YBuildingMemberRl yBuildingMemberRl = buildingMemberRlMapper.selectById(memberRlId);
            MemberUser member = memberService.getById(yBuildingMemberRl.getMemberId());
            PersonsDTO personsDTO = new PersonsDTO();
            personsDTO.setName(" ").setId(Long.parseLong("1"+member.getId())).setTerm("forever");
            if (StringUtils.isNotBlank(member.getIcCard())){
                personsDTO.setWg_card_id(CardConverseUtil.converseTo10Card(member.getIcCard()));
            }
            if (StringUtils.isNotBlank(yBuildingMemberRl.getDeviceRole())) {
              personsDTO.setRole(Integer.valueOf(yBuildingMemberRl.getDeviceRole()));
            }
            // 普通人员
            if (Objects.equals(yBuildingMemberRl.getDeviceRole(), "0")) {
              if (StringUtils.isNotBlank(yBuildingMemberRl.getLiveFloor())) {
                personsDTO.setLive_floor(Integer.valueOf(yBuildingMemberRl.getLiveFloor()));
              }
              if (StringUtils.isNotBlank(yBuildingMemberRl.getHandFloor())) {
                List<Integer> collect = Arrays.stream(yBuildingMemberRl.getHandFloor().split(",")).map(Integer::valueOf).collect(Collectors.toList());
                personsDTO.setHand_floor(collect);
                personsDTO.setHand_floor_count(collect.size());
              }
            } else {
              personsDTO.setHand_floor_count(255);
            }
            persons.add(personsDTO);
          }
          returnMap.put(VERSION, callBackDto.getVersion());
          returnMap.put(CMD, RequestCmd.ADD_PERSON);
          returnMap.put(CMD_NUMBER, event.getId());
          returnMap.put("person_count", persons.size());
          returnMap.put("persons", persons);

        } catch (Exception e) {
          for (String memberId : memberIds.split(",")) {
            YBuildingMemberRl yBuildingMemberRl = buildingMemberRlMapper.selectById(memberId);
            yBuildingMemberRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_ERROR);
            buildingMemberRlMapper.updateById(yBuildingMemberRl);
            event.setStatus("LOCAL_ERROR");
            event.setResponse(Optional.ofNullable(event.getResponse()).orElse("") + "========" + ExceptionUtils.getMessage(e).concat("============".concat(yBuildingMemberRl.getMemberId().toString()) + "^^^^^"));
            eventEntityMapper.updateById(event);
          }
          eventEntityMapper.updateById(event);
          log.error("本地任务发生异常【{}】", ExceptionUtils.getMessage(e));
        }
    }


    private void batchAddVisitor(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
        String visitorIds = event.getBody();
        List<PersonsDTO> persons = new ArrayList<>();
        try {
            for (String visitorId : visitorIds.split(",")) {
                YBuildingVisitorRl yBuildingVisitorRl = buildingVisitorRlMapper.selectById(visitorId);
                Visitor visitor = visitorService.getById(yBuildingVisitorRl.getVisitorId());
                PersonsDTO personsDTO = new PersonsDTO();
                personsDTO.setName(" ").setId(Long.parseLong("2"+visitor.getId())).setTerm("forever");
                if (StringUtils.isNotBlank(visitor.getIcCard())){
                 personsDTO.setWg_card_id(CardConverseUtil.converseTo10Card(visitor.getIcCard()));
                }
                if (StringUtils.isNotBlank(yBuildingVisitorRl.getDeviceRole())) {
                    personsDTO.setRole(Integer.valueOf(yBuildingVisitorRl.getDeviceRole()));
                }
                // 普通人员
                if (Objects.equals(yBuildingVisitorRl.getDeviceRole(), "0")) {
                    if (StringUtils.isNotBlank(yBuildingVisitorRl.getLiveFloor())) {
                        personsDTO.setLive_floor(Integer.valueOf(yBuildingVisitorRl.getLiveFloor()));
                    }
                    if (StringUtils.isNotBlank(yBuildingVisitorRl.getHandFloor())) {
                        List<Integer> collect = Arrays.stream(yBuildingVisitorRl.getHandFloor().split(",")).map(Integer::valueOf).collect(Collectors.toList());
                        personsDTO.setHand_floor(collect);
                        personsDTO.setHand_floor_count(collect.size());
                    }
                } else {
                    personsDTO.setHand_floor_count(255);
                }
                persons.add(personsDTO);
            }
            returnMap.put(VERSION, callBackDto.getVersion());
            returnMap.put(CMD, RequestCmd.ADD_PERSON);
            returnMap.put(CMD_NUMBER, event.getId());
            returnMap.put("person_count", persons.size());
            returnMap.put("persons", persons);

        } catch (Exception e) {
            for (String memberId : visitorIds.split(",")) {
                YBuildingVisitorRl yBuildingVisitorRl = buildingVisitorRlMapper.selectById(memberId);
                yBuildingVisitorRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_ERROR);
                buildingVisitorRlMapper.updateById(yBuildingVisitorRl);
                event.setStatus("LOCAL_ERROR");
                event.setResponse(Optional.ofNullable(event.getResponse()).orElse("") + "========" + ExceptionUtils.getMessage(e).concat("============".concat(yBuildingVisitorRl.getVisitorId().toString()) + "^^^^^"));
                eventEntityMapper.updateById(event);
            }
            eventEntityMapper.updateById(event);
            log.error("本地任务发生异常【{}】", ExceptionUtils.getMessage(e));
        }
    }

    private void deleteAllPerson(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
    returnMap.put(VERSION, callBackDto.getVersion());
    returnMap.put(CMD, RequestCmd.DELETE_PERSON);
    returnMap.put(CMD_NUMBER, event.getId());
    returnMap.put("flag", 0);
  }

  private void deletePerson(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
    String[] split = event.getBody().split(":");
    returnMap.put(VERSION, callBackDto.getVersion());
    returnMap.put(CMD, RequestCmd.DELETE_PERSON);
    returnMap.put(CMD_NUMBER, event.getId());
    returnMap.put("flag", 1);
    returnMap.put("count", 1);
      if (Objects.equals(event.getSysType(),MEMBER)){
          returnMap.put("person_id", Collections.singletonList(Integer.valueOf("1"+split[0])));
      }else if (Objects.equals(event.getSysType(),VISITOR)){
          returnMap.put("person_id", Collections.singletonList(Integer.valueOf("2"+split[0])));
      }
  }

    private void currentDeletePerson(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
        YMemberRecord memberRecord = yMemberRecordService.getById(event.getBody());

        returnMap.put(VERSION, callBackDto.getVersion());
        returnMap.put(CMD, RequestCmd.DELETE_PERSON);
        returnMap.put(CMD_NUMBER, event.getId());
        returnMap.put("flag", 1);
        returnMap.put("count", 1);
        // 区分员工还是访客
        if (ObjectUtil.equal(memberRecord.getType(),0)){
            returnMap.put("person_id", Collections.singletonList(Integer.parseInt("1"+memberRecord.getPersonId())));
        }else {
            returnMap.put("person_id", Collections.singletonList(Integer.parseInt("2"+memberRecord.getPersonId())));
        }
    }



    private void addPerson(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
      // 区分人员还是访客
      if (Objects.equals(event.getSysType(),MEMBER)){
          addMember(callBackDto, returnMap, event);
          // 区分人员还是访客
      }else if (Objects.equals(event.getSysType(),VISITOR)){
          addVisitor(callBackDto, returnMap, event);
      }
  }

    private void addVisitor(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
        String visirorRl = event.getBody();
        YBuildingVisitorRl yBuildingVisitorRl = buildingVisitorRlMapper.selectById(visirorRl);
        if (yBuildingVisitorRl==null){
            event.setStatus("LOCAL_ERROR");
            event.setResponse("访客关联关系已经不存在!");
            eventEntityMapper.updateById(event);
            return;
        }
        Visitor visitor = visitorService.getById(yBuildingVisitorRl.getVisitorId());

        try {
            PersonsDTO personsDTO = new PersonsDTO();
            personsDTO.setName(" ").setId(Long.parseLong("2"+visitor.getId())).setTerm("forever");
            if (StringUtils.isNotBlank(visitor.getIcCard())){
                personsDTO.setWg_card_id(CardConverseUtil.converseTo10Card(visitor.getIcCard()));
            }
            if (StringUtils.isNotBlank(yBuildingVisitorRl.getDeviceRole())) {
                personsDTO.setRole(Integer.valueOf(yBuildingVisitorRl.getDeviceRole()));
            }
            // 普通人员
            if (Objects.equals(yBuildingVisitorRl.getDeviceRole(), "0")) {
                if (StringUtils.isNotBlank(yBuildingVisitorRl.getLiveFloor())) {
                    personsDTO.setLive_floor(Integer.valueOf(yBuildingVisitorRl.getLiveFloor()));
                }
                if (StringUtils.isNotBlank(yBuildingVisitorRl.getHandFloor())) {
                    List<Integer> collect = Arrays.stream(yBuildingVisitorRl.getHandFloor().split(",")).map(Integer::valueOf).collect(Collectors.toList());
                    personsDTO.setHand_floor(collect);
                    personsDTO.setHand_floor_count(collect.size());
                }
            } else {
                personsDTO.setHand_floor_count(255);
            }
            List<PersonsDTO> persons = new ArrayList<>();
            persons.add(personsDTO);
            returnMap.put(VERSION, callBackDto.getVersion());
            returnMap.put(CMD, RequestCmd.ADD_PERSON);
            returnMap.put(CMD_NUMBER, event.getId());
            returnMap.put("person_count", 1);
            returnMap.put("persons", persons);
        } catch (Exception e) {
            yBuildingVisitorRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_ERROR);
            buildingVisitorRlMapper.updateById(yBuildingVisitorRl);
            event.setStatus("LOCAL_ERROR");
            event.setResponse(ExceptionUtils.getMessage(e).concat("============".concat(visitor.getName()).concat("=====").concat(visitor.getId().toString())));
            eventEntityMapper.updateById(event);
            log.error("本地任务发生异常【{}】", ExceptionUtils.getMessage(e));
        }
    }

    private void addMember(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
        String memberRl = event.getBody();
        YBuildingMemberRl yBuildingMemberRl = buildingMemberRlMapper.selectById(memberRl);
        MemberUser member = memberService.getById(yBuildingMemberRl.getMemberId());
        if (member==null){
            buildingMemberRlMapper.deleteById(yBuildingMemberRl);
            event.setStatus("LOCAL_ERROR");
            event.setResponse("人员信息已经删除");
            eventEntityMapper.updateById(event);
            return;
        }
        try {
          PersonsDTO personsDTO = new PersonsDTO();
          personsDTO.setName(" ").setId(Long.parseLong("1"+member.getId())).setTerm("forever");
          if (StringUtils.isNotBlank(member.getIcCard())){
              personsDTO.setWg_card_id(CardConverseUtil.converseTo10Card(member.getIcCard()));
          }
          if (StringUtils.isNotBlank(yBuildingMemberRl.getDeviceRole())) {
            personsDTO.setRole(Integer.valueOf(yBuildingMemberRl.getDeviceRole()));
          }
          // 普通人员
          if (Objects.equals(yBuildingMemberRl.getDeviceRole(), "0")) {
            if (StringUtils.isNotBlank(yBuildingMemberRl.getLiveFloor())) {
              personsDTO.setLive_floor(Integer.valueOf(yBuildingMemberRl.getLiveFloor()));
            }
            if (StringUtils.isNotBlank(yBuildingMemberRl.getHandFloor())) {
              List<Integer> collect = Arrays.stream(yBuildingMemberRl.getHandFloor().split(",")).map(Integer::valueOf).collect(Collectors.toList());
              personsDTO.setHand_floor(collect);
              personsDTO.setHand_floor_count(collect.size());
            }
          } else {
            personsDTO.setHand_floor_count(255);
          }
          List<PersonsDTO> persons = new ArrayList<>();
          persons.add(personsDTO);
          returnMap.put(VERSION, callBackDto.getVersion());
          returnMap.put(CMD, RequestCmd.ADD_PERSON);
          returnMap.put(CMD_NUMBER, event.getId());
          returnMap.put("person_count", 1);
          returnMap.put("persons", persons);
        } catch (Exception e) {
          yBuildingMemberRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_ERROR);
          buildingMemberRlMapper.updateById(yBuildingMemberRl);
          event.setStatus("LOCAL_ERROR");
          event.setResponse(ExceptionUtils.getMessage(e).concat("============".concat(member.getName()).concat("=====").concat(member.getId().toString())));
          eventEntityMapper.updateById(event);
          log.error("本地任务发生异常【{}】", ExceptionUtils.getMessage(e));
        }
    }

    private void updateDeviceParams(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
    returnMap.put(VERSION, callBackDto.getVersion());
    returnMap.put(CMD, RemoteStairsConstant.RequestCmd.UPDATE_DEVICE_PARAMS);
    returnMap.put(CMD_NUMBER, event.getId());
    DeviceDTO deviceDTO = JSON.parseObject(event.getBody(), DeviceDTO.class);
    returnMap.put("device_info", deviceDTO.getDevice_info());
    returnMap.put("server_info", deviceDTO.getServer_info());
    returnMap.put("common_floor", deviceDTO.getCommon_floor());
//        returnMap.put("card_info", deviceDTO.getCard_info());
  }

  private void requestDeviceParams(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
    returnMap.put(VERSION, callBackDto.getVersion());
    returnMap.put(CMD, RequestCmd.REQUEST_DEVICE_PARAMS);
    returnMap.put(CMD_NUMBER, event.getId());
  }

  private void updateSystemTime(CallBackDto callBackDto, Map<String, Object> returnMap, YDeviceEvent event) {
    returnMap.put(VERSION, callBackDto.getVersion());
    returnMap.put(CMD, RequestCmd.UPDATE_SYSTEM_TIME);
    returnMap.put(CMD_NUMBER, event.getId());
    returnMap.put(DATE_TIME, RemoteStairsConstant.dateFormat.format(new Date()));
  }

  private void dealEvent(CallBackDto callBackDto, Map<String, Object> returnMap, YElevatorDevice elevatorDevice) throws ParseException {
    if (callBackDto.getCode() != null && callBackDto.getCode() != 0 && StringUtils.isNotBlank(callBackDto.getErr_desc())) {
      log.error("设备发生错误信息【{}】", JSON.toJSONString(callBackDto));
    }
    switch (callBackDto.getCmd()) {
      //设备发送实时刷卡记录
      case RemoteStairsConstant.CallBackCmd.CARD_REPORT:
        cardReport(callBackDto, elevatorDevice);
        break;

      // 人员数据浏览
      case RequestCmd.BROWSE_PERSONS:
          browsePersons(callBackDto);
          break;

      // 二维码扫描
      case RemoteCardConstant.CallBackCmd.QRCODE_REPORT:
        qrcodeReport(callBackDto, returnMap, elevatorDevice);
        break;

      // 修改设备时间
      case RemoteCardConstant.CallBackCmd.UPDATE_SYSTEM_TIME:
        updateSystemTime(callBackDto, elevatorDevice);
        break;

      //获取设备参数
      case RemoteCardConstant.CallBackCmd.REQUEST_DEVICE_PARAMS:
        requestDeviceParams(callBackDto, elevatorDevice);
        break;

      //修改设备参数
      case RequestCmd.UPDATE_DEVICE_PARAMS:
        updateDeviceParams(callBackDto, elevatorDevice);
        break;

      //删除人员
      case RequestCmd.DELETE_PERSON:
        deletePerson(callBackDto, elevatorDevice);
        break;

      // 新增人员
      case RequestCmd.ADD_PERSON:
        addPerson(callBackDto, elevatorDevice);
        break;

      // 修改人员
      case RequestCmd.UPDATE_PERSON:
        updatePerson(callBackDto);
        break;

      //心跳
      case RemoteCardConstant.CallBackCmd.HEART_BEAT:
          heartBeat(callBackDto, elevatorDevice);
          break;

      // 消防
      case RequestCmd.SET_FIRE:
          setFire(callBackDto, elevatorDevice);
          break;
    }
  }

    private void setFire(CallBackDto callBackDto, YElevatorDevice elevatorDevice) {
        YDeviceEvent eventEntity = eventEntityMapper.selectById(callBackDto.getCmd_number());
        String body = eventEntity.getBody();
        if (Boolean.parseBoolean(body)) {
          elevatorDevice.setFire("TRUE");
          elevatorDeviceService.updateById(elevatorDevice);
        } else {
          elevatorDevice.setFire("FALSE");
          elevatorDeviceService.updateById(elevatorDevice);
        }
        eventEntityMapper.updateEnd(eventEntity.getId());
    }

    private void heartBeat(CallBackDto callBackDto, YElevatorDevice elevatorDevice) {
        elevatorDevice.setLastUpTime(new Date());
        try {
          // 傻逼铁虎 设备时间第一次传20000多年，有的时候还不是时间格式
          Date parse = RemoteStairsConstant.dateFormat.parse(callBackDto.getDate_time());
          if (parse.after(new Date())) {
            elevatorDevice.setDateTime(new Date());
          } else {
            elevatorDevice.setDateTime(parse);
          }
        } catch (Exception e) {
          log.error("铁虎同步时间错误【{}】", ExceptionUtils.getMessage(e));
          elevatorDevice.setDateTime(new Date());
        }
        elevatorDeviceService.updateById(elevatorDevice);
    }

    private void browsePersons(CallBackDto callBackDto) {
        if (callBackDto.getPersons() != null) {
          for (CallBackDto.PersonDto person : callBackDto.getPersons()) {
            YMemberRecord yMemberRecord = new YMemberRecord();
            MemberUser memberUser = memberService.getById(Long.parseLong(person.getId().toString().substring(1)));
            if (memberUser != null) {
              yMemberRecord.setPersonName(memberUser.getName());
              yMemberRecord.setType(0);
            }else {
                Visitor visitor= visitorService.getById(Long.parseLong(person.getId().toString().substring(1)));
                if (visitor!=null){
                    yMemberRecord.setPersonName(visitor.getName());
                    yMemberRecord.setType(1);
                }
            }
            yMemberRecord.setHandfloorcount(person.getHand_floor_count());
            if (CollectionUtils.isNotEmpty(person.getHand_floor())) {
              String collect = person.getHand_floor().stream().map(x -> x + "").collect(Collectors.joining(","));
              yMemberRecord.setHandfloor(collect);
            }
            if (StringUtils.isNotBlank(person.getWg_card_id())) {
              yMemberRecord.setIccard(CardConverseUtil.converseTo16Card(person.getWg_card_id()));
            }
            yMemberRecord.setLivefloor(person.getLive_floor());
            yMemberRecord.setPageno(callBackDto.getPage_no());
            yMemberRecord.setRole(person.getRole());
            yMemberRecord.setPersonId(Long.parseLong(person.getId().toString().substring(1)));
            yMemberRecord.setDeviceNo(callBackDto.getDevice_no());
            yMemberRecord.setTerm(person.getTerm());
            memberRecordMapper.insert(yMemberRecord);
          }
          if (callBackDto.getCount() != 8) {
            eventEntityMapper.updateEnd(callBackDto.getCmd_number());
          } else {
            YDeviceEvent deviceEventEntity = eventEntityMapper.selectById(callBackDto.getCmd_number());
            deviceEventEntity.setBody(callBackDto.getPage_no() + 1 + "");
            eventEntityMapper.updateById(deviceEventEntity);
          }
        }
    }


    private void updatePerson(CallBackDto callBackDto) {
        YDeviceEvent eventEntity = eventEntityMapper.selectById(callBackDto.getCmd_number());
        // 区分人员还是访客
        if (Objects.equals(eventEntity.getSysType(),MEMBER)){
            memberUpdatePerson(callBackDto,eventEntity);
            // 区分人员还是访客
        }else if (Objects.equals(eventEntity.getSysType(),VISITOR)){
            visitorUpdatePerson(callBackDto,eventEntity);
        }
    }

    private void memberUpdatePerson(CallBackDto callBackDto,YDeviceEvent eventEntity) {
        if ((callBackDto.getCode() != null && callBackDto.getCode() != 0) || StringUtils.isNotBlank(callBackDto.getErr_desc())) {
          YBuildingMemberRl yBuildingMemberRl = buildingMemberRlMapper.selectById(eventEntity.getBody());
          yBuildingMemberRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_ERROR);
          buildingMemberRlMapper.updateById(yBuildingMemberRl);
          eventEntityMapper.updateEnd(eventEntity.getId());
          log.error("修改人员失败【{}】【{}】", callBackDto.getDevice_no(), yBuildingMemberRl.getId());
        } else {
          YBuildingMemberRl yBuildingMemberRl = buildingMemberRlMapper.selectById(eventEntity.getBody());
          yBuildingMemberRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_SUCCESS);
          buildingMemberRlMapper.updateById(yBuildingMemberRl);
          eventEntityMapper.updateEnd(eventEntity.getId());
        }
    }

    private void visitorUpdatePerson(CallBackDto callBackDto,YDeviceEvent eventEntity) {
        if ((callBackDto.getCode() != null && callBackDto.getCode() != 0) || StringUtils.isNotBlank(callBackDto.getErr_desc())) {
            YBuildingVisitorRl buildingVisitorRl = buildingVisitorRlMapper.selectById(eventEntity.getBody());
            buildingVisitorRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_ERROR);
            buildingVisitorRlMapper.updateById(buildingVisitorRl);
            eventEntityMapper.updateEnd(eventEntity.getId());
            log.error("修改访客失败【{}】【{}】", callBackDto.getDevice_no(), buildingVisitorRl.getId());
        } else {
            YBuildingVisitorRl buildingVisitorRl = buildingVisitorRlMapper.selectById(eventEntity.getBody());
            buildingVisitorRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_SUCCESS);
            buildingVisitorRlMapper.updateById(buildingVisitorRl);
            eventEntityMapper.updateEnd(eventEntity.getId());
        }
    }

    private void addPerson(CallBackDto callBackDto, YElevatorDevice elevatorDevice) {
    YDeviceEvent eventEntity = eventEntityMapper.selectById(callBackDto.getCmd_number());
    // 楼栋发生变更第二部  新增人员信息
    if (Objects.equals(eventEntity.getType(), RequestCmd.BATCH_ADD_PERSON)) {
        // 区分人员还是访客
        if (Objects.equals(eventEntity.getSysType(),MEMBER)){
            batchAddMember(elevatorDevice, eventEntity);
            // 区分人员还是访客
        }else if (Objects.equals(eventEntity.getSysType(),VISITOR)){
            batchAddVisitor(elevatorDevice,eventEntity);
        }
        // 新增人员信息
    } else if (Objects.equals(eventEntity.getType(), RequestCmd.ADD_PERSON)) {
        // 区分人员还是访客
        if (Objects.equals(eventEntity.getSysType(),MEMBER)){
            memberAddPerson(eventEntity);
            // 区分人员还是访客
        }else if (Objects.equals(eventEntity.getSysType(),VISITOR)){
            visitorAddPerson(eventEntity);
        }
    }
  }
    private void visitorAddPerson(YDeviceEvent eventEntity) {
        YBuildingVisitorRl buildingVisitorRl = buildingVisitorRlMapper.selectById(eventEntity.getBody());
        buildingVisitorRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_SUCCESS);
        buildingVisitorRlMapper.updateById(buildingVisitorRl);
        eventEntityMapper.updateEnd(eventEntity.getId());
    }

    private void memberAddPerson(YDeviceEvent eventEntity) {
        YBuildingMemberRl yBuildingMemberRl = buildingMemberService.getById(eventEntity.getBody());
        yBuildingMemberRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_SUCCESS);
        buildingMemberService.updateById(yBuildingMemberRl);
        eventEntityMapper.updateEnd(eventEntity.getId());
    }

    private void batchAddVisitor(YElevatorDevice elevatorDevice, YDeviceEvent eventEntity) {
        for (String visitorRlId : eventEntity.getBody().split(",")) {
            YBuildingVisitorRl yBuildingVisitorRl = buildingVisitorRlMapper.selectById(visitorRlId);
            yBuildingVisitorRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_SUCCESS);
            buildingVisitorRlMapper.updateById(yBuildingVisitorRl);
        }
        List<YBuildingVisitorRl> yBuildingMemberRls = buildingVisitorRlMapper.selectList(new LambdaQueryWrapper<YBuildingVisitorRl>().eq(YBuildingVisitorRl::getDeviceId,elevatorDevice.getId()).eq(YBuildingVisitorRl::getDeviceSyncStatus,DeviceSyncStatus.UN_SYNC));
        if (CollectionUtils.isEmpty(yBuildingMemberRls)) {
            elevatorDevice.setMemberSyncStatus(MemberSyncStatus.SUCCESS);
            elevatorDeviceService.updateById(elevatorDevice);
        }
        eventEntityMapper.updateEnd(eventEntity.getId());
    }

    private void batchAddMember(YElevatorDevice elevatorDevice, YDeviceEvent eventEntity) {
        for (String memberRlId : eventEntity.getBody().split(",")) {
          YBuildingMemberRl yBuildingMemberRl = buildingMemberService.getById(memberRlId);
          yBuildingMemberRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_SUCCESS);
          buildingMemberRlMapper.updateById(yBuildingMemberRl);
        }
        List<YBuildingMemberRl> yBuildingMemberRls = buildingMemberRlMapper.selectAllByDeviceId(elevatorDevice.getId(), DeviceSyncStatus.UN_SYNC);
        if (CollectionUtils.isEmpty(yBuildingMemberRls)) {
          elevatorDevice.setMemberSyncStatus(MemberSyncStatus.SUCCESS);
          elevatorDeviceService.updateById(elevatorDevice);
        }
        eventEntityMapper.updateEnd(eventEntity.getId());
    }

    private void deletePerson(CallBackDto callBackDto, YElevatorDevice elevatorDevice) {
    YDeviceEvent eventEntity = eventEntityMapper.selectById(callBackDto.getCmd_number());
    if (Objects.equals(eventEntity.getType(), RequestCmd.DELETE_ALL_PERSON)) {
      if ((callBackDto.getCode() != null && callBackDto.getCode() != 0) || StringUtils.isNotBlank(callBackDto.getErr_desc())) {
        log.error("删除设备失败【{}】", callBackDto.getDevice_no());
        elevatorDevice.setMemberSyncStatus(MemberSyncStatus.DELETE_ERROR);
        elevatorDeviceService.updateById(elevatorDevice);
        eventEntityMapper.updateEnd(eventEntity.getId());
      } else {
          // 人员删除全部记录信息
          memberDeleteAllPerson(elevatorDevice, eventEntity);
          VisitorDeleteAllPerson(elevatorDevice, eventEntity);
      }
      // 删除单个人员信息
    } else if (Objects.equals(eventEntity.getType(), RequestCmd.DELETE_PERSON)) {
        // 区分人员还是访客
        if (Objects.equals(eventEntity.getSysType(),MEMBER)){
            memberDeletePerson(elevatorDevice, eventEntity);
        }else if (Objects.equals(eventEntity.getSysType(),VISITOR)){
            visitorDeletePerson(elevatorDevice, eventEntity);
        }
    } else if (Objects.equals(eventEntity.getType(),RequestCmd.CURRENT_DELETE_PERSON)){
        yMemberRecordService.removeById(Long.parseLong(eventEntity.getBody()));
        eventEntityMapper.updateEnd(eventEntity.getId());
    }
  }

    private void memberDeletePerson(YElevatorDevice elevatorDevice, YDeviceEvent eventEntity) {
        // 删除中间表信息
        String[] split = eventEntity.getBody().split(":");
        buildingMemberService.deleteByMemberIdAndDeviceId(elevatorDevice.getId(), Long.parseLong(split[1]));
        eventEntityMapper.updateEnd(eventEntity.getId());
    }

    private void visitorDeletePerson(YElevatorDevice elevatorDevice, YDeviceEvent eventEntity) {
        // 删除中间表信息
        String[] split = eventEntity.getBody().split(":");
        buildingVisitorRlMapper.delete(new LambdaQueryWrapper<YBuildingVisitorRl>()
                .eq(YBuildingVisitorRl::getDeviceId,elevatorDevice.getId())
                .eq(YBuildingVisitorRl::getVisitorId, Long.parseLong(split[1])));
        eventEntityMapper.updateEnd(eventEntity.getId());
    }


    private void memberDeleteAllPerson(YElevatorDevice elevatorDevice, YDeviceEvent eventEntity) {
        // 中间表删除全部信息
        buildingMemberService.remove(new LambdaQueryWrapper<YBuildingMemberRl>().eq(YBuildingMemberRl::getDeviceId, elevatorDevice.getId()));
        // 删除设备信息
        elevatorDeviceService.removeById(elevatorDevice);
        // 人员历史表删除全部信息
        memberRecordMapper.deleteByDeviceId(elevatorDevice.getDeviceNo());
        eventEntity.setStatus(DeviceEvent.END);
        eventEntityMapper.updateEnd(eventEntity.getId());
    }


    private void VisitorDeleteAllPerson(YElevatorDevice elevatorDevice, YDeviceEvent eventEntity) {
        // 中间表删除全部信息
        buildingVisitorRlMapper.delete(new LambdaQueryWrapper<YBuildingVisitorRl>().eq(YBuildingVisitorRl::getDeviceId, elevatorDevice.getId()));
        eventEntity.setStatus(DeviceEvent.END);
        eventEntityMapper.updateEnd(eventEntity.getId());
    }

    private void updateSystemTime(CallBackDto callBackDto, YElevatorDevice elevatorDevice) {
    elevatorDevice.setDateTime(new Date());
    elevatorDeviceService.updateById(elevatorDevice);
    eventEntityMapper.updateEnd(callBackDto.getCmd_number());
  }

  private void updateDeviceParams(CallBackDto callBackDto, YElevatorDevice elevatorDevice) {
    elevatorDevice.setFiledStatus(ElevatorFiledStatus.NO_SYNC);
    elevatorDeviceService.updateById(elevatorDevice);
    eventEntityMapper.updateEnd(callBackDto.getCmd_number());
  }

  private void requestDeviceParams(CallBackDto callBackDto, YElevatorDevice elevatorDevice) throws ParseException {
    if (callBackDto.getDevice_info().getFirst_floor() != null) {
      elevatorDevice.setFirstFloor(callBackDto.getDevice_info().getFirst_floor().toString());
    } else {
      elevatorDevice.setFirstFloor(null);
    }
    if (callBackDto.getDevice_info().getDelay_time() != null) {
      elevatorDevice.setDelayTime(callBackDto.getDevice_info().getDelay_time().toString());
    } else {
      elevatorDevice.setDelayTime(null);
    }
    if (callBackDto.getDevice_info().getVolume() != null) {
      elevatorDevice.setVolume(callBackDto.getDevice_info().getVolume().toString());
    } else {
      elevatorDevice.setVolume(null);
    }
    if (callBackDto.getDevice_info().getRemind() != null) {
      elevatorDevice.setRemind(callBackDto.getDevice_info().getRemind().toString());
    } else {
      elevatorDevice.setRemind(null);
    }


    try {
      // 傻逼铁虎 设备时间第一次传20000多年，有的时候还不是时间格式
      Date parse = RemoteStairsConstant.dateFormat.parse(callBackDto.getDate_time());
      if (parse.after(new Date())) {
        elevatorDevice.setDateTime(new Date());
      } else {
        elevatorDevice.setDateTime(parse);
      }
    } catch (Exception e) {
      log.error("铁虎同步时间错误【{}】", ExceptionUtils.getMessage(e));
      elevatorDevice.setDateTime(new Date());
    }

    elevatorDevice.setFirmware(callBackDto.getDevice_info().getFirmware());
    if (callBackDto.getDevice_info().getQr_mode() != null) {
      elevatorDevice.setQrMode(callBackDto.getDevice_info().getQr_mode().toString());
    } else {
      elevatorDevice.setQrMode(null);
    }
    elevatorDevice.setIp(callBackDto.getServer_info().getServer_ip());
    if (callBackDto.getServer_info().getServer_port() != null) {
      elevatorDevice.setPort(callBackDto.getServer_info().getServer_port().toString());
    } else {
      elevatorDevice.setPort(null);
    }
    elevatorDevice.setPreventCopy(callBackDto.getCard_info().getPrevent_copy());
    elevatorDevice.setCommCount(Optional.ofNullable(callBackDto.getCommon_floor().getComm_count()).orElse(0));
    if (CollectionUtils.isNotEmpty(callBackDto.getCommon_floor().getFloor())) {
      elevatorDevice.setCommFloor(Joiner.on(",").join(callBackDto.getCommon_floor().getFloor()));
    } else {
      elevatorDevice.setCommFloor(null);
    }
    elevatorDevice.setDeviceNo(callBackDto.getDevice_no());
    elevatorDevice.setFiledStatus(ElevatorFiledStatus.SYNC);
    elevatorDeviceService.updateById(elevatorDevice);
    eventEntityMapper.updateEnd(callBackDto.getCmd_number());
  }

  private void qrcodeReport(CallBackDto callBackDto, Map<String, Object> returnMap, YElevatorDevice elevatorDevice) throws ParseException {
    String[] data = callBackDto.getData().split("_");
    if (Objects.equals(data[1], "m")) {
      memberQrcodeReport(callBackDto, returnMap, elevatorDevice, data);
    } else if (Objects.equals(data[1], "v")) {
      visitorQrcodeReport(data, callBackDto, returnMap, elevatorDevice);
    }else if (Objects.equals(data[1], "d")) {
        visitorQrcodeReport(data, callBackDto, returnMap, elevatorDevice);
    }
  }

  private void memberQrcodeReport(CallBackDto callBackDto, Map<String, Object> returnMap, YElevatorDevice elevatorDevice, String[] data) {
    MemberUser member = memberService.getById(Long.parseLong(data[3].substring(1)));
    returnMap.put("token_code", callBackDto.getToken_code());
    if (member == null) {
      returnMap.put("text", "找不到该人员信息！");
      setBaseResponse(returnMap, RemoteCardConstant.CallBackCmd.QRCODE_REPORT);
      return;
    }

    YElevatorMemberRecord record = new YElevatorMemberRecord();
    record.setMemberId(Integer.parseInt(data[3].substring(1)));
    record.setIcCard("");
    record.setStatus("0");
    record.setName(member.getName());
    record.setUnlockType("4");
    record.setTimeStamp(new Date());
    record.setDeviceId(elevatorDevice.getId());
    record.setDeviceName(elevatorDevice.getName());
    String expireTime = data[2];
    try {
      Date expireDate = RemoteStairsConstant.QRCodeDateFormat.parse(expireTime);
      Calendar instance = Calendar.getInstance();
      instance.setTime(expireDate);
      instance.add(Calendar.MINUTE, +5);
      if (instance.getTime().before(new Date())) {
        record.setStatus("5");
        record.setRole("0");
        memberRecordService.save(record);
        returnMap.put("text", "二维码已经失效");
        setBaseResponse(returnMap, RemoteCardConstant.CallBackCmd.QRCODE_REPORT);
        return;
      }
    } catch (ParseException e) {
      log.error("时间解析失败【{}】人员id【{}】", expireTime, member.getId());
    }


    YBuildingMemberRl memberRl = buildingMemberRlMapper.selectByMemberIdAndDeviceId(elevatorDevice.getId(), member.getId());

    // 查找关系表 返回楼层权限数据
    if (memberRl == null) {
      record.setStatus("3");
      record.setRole("0");
      memberRecordService.save(record);
      returnMap.put("text", "无权限！");
      setBaseResponse(returnMap, RemoteCardConstant.CallBackCmd.QRCODE_REPORT);
      return;
    }

    Integer cmd_number = buildingMemberRlMapper.selectMemberDeiviceId(member.getId(), elevatorDevice.getId());
//    if (memberRl.getLiveFloor() != null) {
//      returnMap.put("live_floor", Integer.valueOf(memberRl.getLiveFloor()));
//    }
    if (Objects.equals(memberRl.getDeviceRole(), "1")) {
      returnMap.put("hand_floor_count", 255);
      returnMap.put("hand_floor", new ArrayList<>());
    } else {
      if (StringUtils.isNotBlank(memberRl.getHandFloor())) {
        String[] split = memberRl.getHandFloor().split(",");
        List<Integer> collect = Arrays.stream(split).map(Integer::valueOf).collect(Collectors.toList());
        returnMap.put("hand_floor_count", split.length);
        returnMap.put("hand_floor", collect);
      }
    }
    record.setRole(memberRl.getDeviceRole());

    YBuliding yBuliding = bulidingMapper.selectById(elevatorDevice.getBuildingId());
    if (yBuliding != null) {
      record.setBuildingName(yBuliding.getName());
    }
    memberRecordService.save(record);
    returnMap.put("cmd_number", cmd_number);
    setBaseResponse(returnMap, RemoteCardConstant.CallBackCmd.QRCODE_REPORT);
  }


  private void visitorQrcodeReport(String[] data, CallBackDto callBackDto, Map<String, Object> returnMap, YElevatorDevice elevatorDevice) throws ParseException {
    Visitor visitor = visitorService.getById(data[3].substring(1));
    returnMap.put("token_code", callBackDto.getToken_code());
    if (visitor == null) {
      returnMap.put("text", "找不到该访客信息！");
      setBaseResponse(returnMap, RemoteCardConstant.CallBackCmd.QRCODE_REPORT);
      return;
    }

    if (!ObjectUtil.equal(visitor.getStatus(),"1")){
      returnMap.put("text", "访客状态异常！");
      setBaseResponse(returnMap, RemoteCardConstant.CallBackCmd.QRCODE_REPORT);
      return;
    }
    YElevatorVisitorMemberRecord visitorMemberRecord = new YElevatorVisitorMemberRecord();
    visitorMemberRecord.setVisitorMemberId(visitor.getId());
    visitorMemberRecord.setDeviceId(elevatorDevice.getId());
    visitorMemberRecord.setVisitorMemberName(visitor.getName());
    visitorMemberRecord.setStatus("0");
    visitorMemberRecord.setUnlockType("4");
    visitorMemberRecord.setDeviceName(elevatorDevice.getName());
    visitorMemberRecord.setTimeStamp(RemoteStairsConstant.dateFormat.parse(callBackDto.getTime_stamp()));
    YBuliding yBuliding = bulidingMapper.selectById(elevatorDevice.getBuildingId());
    if (yBuliding != null) {
      visitorMemberRecord.setBuildingName(yBuliding.getName());
    }

    if (data[1].equals("v")){
        String expireTime = data[2];
        try {
            Date expireDate = RemoteStairsConstant.QRCodeDateFormat.parse(expireTime);
            Calendar instance = Calendar.getInstance();
            instance.setTime(expireDate);
            instance.add(Calendar.MINUTE, +5);
            if (!Objects.equals(visitor.getSource(),3)&&instance.getTime().before(new Date())) {
                visitorMemberRecord.setStatus("5");
                visitorMemberRecordService.save(visitorMemberRecord);
                returnMap.put("text", "二维码已经失效");
                setBaseResponse(returnMap, RemoteCardConstant.CallBackCmd.QRCODE_REPORT);
                return;
            }
        } catch (ParseException e) {
            log.error("时间解析失败【{}】访客id【{}】", expireTime, visitor.getId());
        }
    }



    // 访客时间判断
    if (visitor.getVisitEndDate().before(new Date()) || visitor.getVisitStartDate().after(new Date())) {
      visitorMemberRecord.setStatus("3");
      visitorMemberRecordService.save(visitorMemberRecord);
      returnMap.put("text", "已经过期！");
      setBaseResponse(returnMap, RemoteCardConstant.CallBackCmd.QRCODE_REPORT);
      return;
    }


    // 查找关系表 返回楼层权限数据
    YBuildingVisitorRl buildingVisitorRl = buildingVisitorRlMapper.selectByVisitorIdAndDeviceId(visitor.getId(), elevatorDevice.getId());
    if (buildingVisitorRl == null) {
      visitorMemberRecord.setStatus("3");
      visitorMemberRecordService.save(visitorMemberRecord);
      returnMap.put("text", "无权限！");
      setBaseResponse(returnMap, RemoteCardConstant.CallBackCmd.QRCODE_REPORT);
      return;
    }

    Integer cmd_number = buildingVisitorRlMapper.selectVisitorDeiviceId(visitor.getId(), elevatorDevice.getId());

//    if (buildingVisitorRl.getLiveFloor() != null) {
//      returnMap.put("live_floor", Integer.valueOf(buildingVisitorRl.getLiveFloor()));
//    }
    if (Objects.equals(buildingVisitorRl.getDeviceRole(), "1")) {
      returnMap.put("hand_floor_count", 255);
      returnMap.put("hand_floor", new ArrayList<>());
    } else {
      if (StringUtils.isNotBlank(buildingVisitorRl.getHandFloor())) {
        String[] split = buildingVisitorRl.getHandFloor().split(",");
        List<Integer> collect = Arrays.stream(split).map(Integer::valueOf).collect(Collectors.toList());
        returnMap.put("hand_floor_count", split.length);
        returnMap.put("hand_floor", collect);
      }
    }

    returnMap.put("cmd_number", cmd_number);
    visitorMemberRecordService.save(visitorMemberRecord);
    setBaseResponse(returnMap, RemoteCardConstant.CallBackCmd.QRCODE_REPORT);
  }

  private void cardReport(CallBackDto callBackDto, YElevatorDevice elevatorDevice) throws ParseException {
      MemberUser memberUser = memberService.getById(Long.parseLong(callBackDto.getPerson_id().toString().substring(1)));
      if (memberUser!=null){
          memberCardReport(callBackDto, elevatorDevice,memberUser);
      }else {
          Visitor visitor = visitorService.getById(Long.parseLong(callBackDto.getPerson_id().toString().substring(1)));
          if (visitor!=null){
              visitorCardReport(callBackDto, elevatorDevice,visitor);
          }else {
              log.error("刷卡记录查询失败！ 找不到匹配的人员信息！只保存访客记录！");
              visitorCardReport(callBackDto, elevatorDevice,null);

          }
      }
  }


    private void visitorCardReport(CallBackDto callBackDto, YElevatorDevice elevatorDevice,Visitor visitor) throws ParseException {
        YElevatorVisitorMemberRecord memberRecord = new YElevatorVisitorMemberRecord();
        memberRecord.setVisitorMemberId(callBackDto.getPerson_id()==null?null:Long.parseLong(callBackDto.getPerson_id().toString().substring(1)))
                .setDeviceId(elevatorDevice.getId())
                .setStatus(callBackDto.getStatus())
                .setTimeStamp(RemoteStairsConstant.dateFormat.parse(callBackDto.getTime_stamp()))
                .setUnlockType(callBackDto.getUnlock_type());
        if (StringUtils.isNotBlank(callBackDto.getCard_id())&&ObjectUtil.equal(callBackDto.getUnlock_type(),"1")) {
            memberRecord.setIcCard(CardConverseUtil.converseTo16Card(callBackDto.getCard_id()));
        }
        if (visitor != null) {
            memberRecord.setVisitorMemberName(visitor.getName());
        }
        YBuliding yBuliding = bulidingMapper.selectById(elevatorDevice.getBuildingId());
        if (yBuliding != null) {
            memberRecord.setBuildingName(yBuliding.getName());
        }
        memberRecord.setDeviceName(elevatorDevice.getName());
        visitorMemberRecordService.save(memberRecord);
    }

    private void memberCardReport(CallBackDto callBackDto, YElevatorDevice elevatorDevice,MemberUser memberUser) throws ParseException {
        YElevatorMemberRecord memberRecord = new YElevatorMemberRecord();
        memberRecord.setMemberId(Integer.parseInt(callBackDto.getPerson_id().toString().substring(1)))
                .setDeviceId(elevatorDevice.getId())
                .setRole(callBackDto.getRole())
                .setStatus(callBackDto.getStatus())
                .setTimeStamp(RemoteStairsConstant.dateFormat.parse(callBackDto.getTime_stamp()))
                .setUnlockType(callBackDto.getUnlock_type());
        if (StringUtils.isNotBlank(callBackDto.getCard_id())&&ObjectUtil.equal(callBackDto.getUnlock_type(),"1")) {

          memberRecord.setIcCard(CardConverseUtil.converseTo16Card(callBackDto.getCard_id()));
        }
        if (memberUser != null) {
          memberRecord.setName(memberUser.getName());
        }
        YBuliding yBuliding = bulidingMapper.selectById(elevatorDevice.getBuildingId());
        if (yBuliding != null) {
          memberRecord.setBuildingName(yBuliding.getName());
        }
        memberRecord.setDeviceName(elevatorDevice.getName());
        memberRecordService.save(memberRecord);
    }

    private void card(CallBackDto callBackDto, Map<String, Object> returnMap, YCardDevice cardDevice) throws Exception {
    switch (callBackDto.getCmd()) {
      // 心跳
      case RemoteCardConstant.CallBackCmd.HEART_BEAT:
        cardDevice.setLastUpTime(new Date());
        cardDevice.setStatus("1");
        cardDeviceService.updateById(cardDevice);
        break;

      //发卡器感应卡片
      case RemoteCardConstant.CallBackCmd.CARD_REPORT:
        cardReport(callBackDto, cardDevice);
        break;
    }
  }

  private void cardReport(CallBackDto callBackDto, YCardDevice cardDevice) throws Exception {
    // 保存人员卡号信息
    MemberUser member = memberService.getOne(new LambdaQueryWrapper<MemberUser>().eq(MemberUser::getReadCardStatus, CardStatus.BEGIN));
    if (member != null) {

      String saveCard = CardConverseUtil.converseTo16Card(callBackDto.getCard_id());
      MemberUser byIcCard = memberService.getOne(new LambdaQueryWrapper<MemberUser>().eq(MemberUser::getIcCard, saveCard));
      // 卡号被别人征用了
      if (byIcCard != null) {
        member.setReadCardStatus(CardStatus.REPEAT);
        memberService.updateById(member);
      } else {
        // 保存人员卡号信息
        member.setIcCard(saveCard);
        member.setReadCardStatus(CardStatus.END);
        memberService.updateById(member);
          // 通知其他设备人员删除处理
          reactor.notify(EventTopic.MEMBER_UPDATE_CARD, Event.wrap(member.getId()));
        //发送人员修改
        List<YBuildingMemberRl> list = buildingMemberService.findList(new YBuildingMemberRlParam().setMemberId(member.getId()));
        if (CollectionUtils.isNotEmpty(list)) {
          for (YBuildingMemberRl yBuildingMemberRl : list) {
            // 修改卡号
            yBuildingMemberRl.setDeviceSyncStatus(DeviceSyncStatus.UPDATE);
            buildingMemberService.updateById(yBuildingMemberRl);
            // 插入人员修改任务表
            YElevatorDevice device = elevatorDeviceService.getById(yBuildingMemberRl.getDeviceId());
            YDeviceEvent deviceEvent = new YDeviceEvent();
            deviceEvent.setDeviceNo(device.getDeviceNo());
            deviceEvent.setStatus(DeviceEvent.NEW);
            deviceEvent.setCreateDate(new Date());
            deviceEvent.setSysType(1);
            deviceEvent.setBody(yBuildingMemberRl.getId().toString());
            deviceEvent.setType(RequestCmd.UPDATE_PERSON);
            eventEntityMapper.insert(deviceEvent);
          }
        }
      }
    } else {
      log.error("未找到读卡的人员跳过此次读卡信息!");
    }
  }


  @Data
  public static class Test{
        private String keyword;
        private String type;
    }


  private void setBaseResponse(Map<String, Object> returnMap, String cmd) {
    returnMap.put("response", "ACK");
    returnMap.put("cmd", cmd);
    returnMap.put("code", 0);
  }

}
